package com.lvcoding.secdemo1.controller;

import com.google.code.kaptcha.Producer;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@Controller
public class KaptchaController {

	@Autowired
	private Producer producer;

	@SneakyThrows
	@GetMapping("kaptcha")
	public void creatKaptcha(HttpServletRequest request, HttpServletResponse response) {
		String text = producer.createText();
		request.getSession().setAttribute("kaptcha", text);
		BufferedImage image = producer.createImage(text);
		ServletOutputStream outputStream = response.getOutputStream();
		ImageIO.write(image, "png", outputStream);
	}

}
